package com.wf.userManagement.utils;

import cn.hutool.core.util.StrUtil;
import com.wf.apicommons.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Random;


/**
 * @Description: 验证码工具类
 */
@Service
public class VerificationCodeUtil {

    @Autowired
    private RedisUtils ru;


    /**
     * 每个缓存生效时间5分钟
     */
    public static final long CACHE_HOLD_TIME = 5 * 60L;
    /**
     * 缓存的KEY
     */
    public static final String CODE_KEY = "_codeKey";

    /**
     * 存放一个缓存对象
     *
     * @param cacheKey 缓存的key  缓存的key
     * @param code    缓存的值value
     */
    public  void put(String cacheKey, String code) {
        put(cacheKey, code, CACHE_HOLD_TIME);

    }

    /**
     * 存放一个缓存对象
     *
     * @param cacheKey 缓存的key  缓存的key
     */
    public  String put(String cacheKey) {
        String code = getCode();
        put(cacheKey, code, CACHE_HOLD_TIME);
        return code;
    }


    /**
     * 存放一个缓存对象，保存时间为holdTime
     *
     * @param cacheKey 缓存的key
     * @param code      缓存的值
     * @param holdTime 过期时间
     */
    public  void put(String cacheKey, String code, long holdTime) {
        ru.set(getCacheKey(cacheKey), code,holdTime);
    }

    /**
     * 删除某个缓存
     *
     * @param cacheKey 缓存的key
     */
    public  void remove(String cacheKey) {
       ru.deleteKey(getCacheKey(cacheKey));
    }


    /**
     * 检查缓存对象是否存在，
     * 若不存在，则返回false
     * 若存在，检查其是否已过有效期，如果已经过了则删除该缓存并返回false
     *
     * @param cacheKey 缓存的key
     * @return true or false
     */
    public  boolean checkCacheKey(String cacheKey,String code) {
        Long holdTime = ru.getExpire(getCacheKey(cacheKey));
        if (holdTime == null || holdTime == -2L) {
            return false;
        }

        String code2=ru.get(getCacheKey(cacheKey)).toString();
        if(!StrUtil.equals(code2,code)){
            return false;
        }
        remove(cacheKey);
        return true;
    }


    /**
     * 处理缓存的数据key
     * @param cacheKey
     * @return
     */
    private String getCacheKey(String cacheKey){
        return cacheKey.concat(CODE_KEY);
    }


    /**
     * 随机生成验证码
     *
     * @return 返回验证码
     */
    private String getCode() {
        int n = 6;
        StringBuilder code = new StringBuilder();
        Random ran = new Random();
        for (int i = 0; i < n; i++) {
            code.append(Integer.valueOf(ran.nextInt(10)).toString());
        }
        return code.toString();
    }

}
